﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using System.Xml.Serialization;

namespace MonoSettlers
{
    public static class RaceConfigLoader
    {
        public static RaceConfig Open(String inXMLPath)
        {
            var reader = new XmlSerializer(typeof(RaceConfig));
            var stream = System.IO.File.OpenRead(inXMLPath);
            RaceConfig result;

            using (stream)
            {
                result = (RaceConfig)reader.Deserialize(stream);
            }

            foreach (var buildable in result.Buildables)
            {
                AnimationClass animClass = AnimationLibrary.Instance.FindClass(buildable.AnimationClass);

                buildable.VisualWidth = animClass.AmbientSet.Width;
                buildable.VisualHeight = animClass.AmbientSet.Height;
                buildable.GridHeight = (int)Math.Ceiling((double)(buildable.VisualHeight / 25));
                buildable.GridWidth = (int)Math.Ceiling((double)(buildable.VisualWidth / 25));

                int minYSolid = buildable.VisualHeight;
                foreach (var solid in animClass.SolidBoundaries)
                {
                    Rectangle intSolid = new Rectangle()
                    {
                        X = (int)(solid.X),
                        Y = (int)(solid.Y),
                        Width = (int)(solid.W),
                        Height = (int)(solid.Z)
                    };

                    if (intSolid.Y < minYSolid)
                        minYSolid = intSolid.Y;

                    buildable.SolidBoundaries.Add(intSolid);
                }

                buildable.LockedBounds = new Rectangle()
                {
                    X = 0,
                    Y = minYSolid,
                    Width = buildable.VisualWidth,
                    Height = buildable.VisualHeight - minYSolid,
                };

                for (int i = 0; i < buildable.ResourceStacks.Count; i++)
                {
                    ResourceStackConfig stackCfg = buildable.ResourceStacks[i];

                    stackCfg.MaxStackSize = (stackCfg.MaxStackSize == 0) ? GenericResourceStack.MAX_STACK_SIZE : stackCfg.MaxStackSize;

                    stackCfg.DoublePosition = new Vector2d(
                        animClass.ResourceStacks[i].X,
                        animClass.ResourceStacks[i].Y);

                    if (stackCfg.TimeOffset == 0)
                    {
                        if (stackCfg.Direction == StackDirection.Incoming)
                        {

                        }
                    }
                }
            }

            return result;
        }
    }
}
